package com.jltx.xq.relaxnewspro.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.jltx.xq.relaxnewspro.R;
import com.jltx.xq.relaxnewspro.framework.App;
import com.jltx.xq.relaxnewspro.framework.BaseAppCompatActivity;
import com.jltx.xq.relaxnewspro.utils.DisplayUtil;
import com.jltx.xq.relaxnewspro.utils.HttpUtil;
import com.jltx.xq.relaxnewspro.utils.Settings;
import com.jltx.xq.relaxnewspro.utils.Utils;
import com.jltx.xq.relaxnewspro.utils.XqLog;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

/**
 * Created by bo on 2017/5/5.
 */

public abstract class BaseDetailsActivity extends BaseAppCompatActivity {
    protected boolean isCollected;
    protected NestedScrollView scrollView;
    protected Toolbar toolbar;
    protected WebView contentView;
    protected ImageView topImage;
    protected FrameLayout mainContent;
    protected ProgressBar progressBar;
    protected ProgressBar progressBarTopPic;
    protected ImageButton networkBtn;

    protected abstract void onDataRefresh();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //全屏，状态栏浮在activity上面
        }
        super.onCreate(savedInstanceState);
        loadSetings();
        setContentView(getLayoutID());

    }

    protected void initView(){

        int statusHeight = DisplayUtil.getStatusBarHeight(App.getApp().getApplicationContext());
        View stbarView = (View) findViewById(R.id.stbar);
        LinearLayout.LayoutParams llp = (LinearLayout.LayoutParams) stbarView.getLayoutParams();
        llp.height = statusHeight;
        stbarView.setLayoutParams(llp);

        mainContent = (FrameLayout) findViewById(R.id.main_content);
        scrollView = (NestedScrollView) findViewById(R.id.scrollView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        progressBarTopPic = (ProgressBar) findViewById(R.id.progressBarTopPic);
        networkBtn = (ImageButton) findViewById(R.id.networkBtn);
        topImage = (ImageView) findViewById(R.id.topImage);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        getSupportActionBar().setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.top_gradient));
        contentView = (WebView) findViewById(R.id.content_view);
        FrameLayout.LayoutParams flParams = (FrameLayout.LayoutParams)scrollView.getLayoutParams();
        flParams.topMargin = statusHeight;
        scrollView.setLayoutParams(flParams);
        contentView.getSettings().setJavaScriptEnabled(true);
        contentView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        contentView.getSettings().setDomStorageEnabled(true);
        contentView.getSettings().setDatabaseEnabled(true);
        contentView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                XqLog.d("TTTTT","onPageStarted.url:"+url);
                super.onPageStarted(view, url, favicon);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                XqLog.d("TTTTT","onPageFinished.url:"+url);
                hideContentLoading();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                displayNetworkError();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                contentView.loadUrl(url);
                XqLog.d("TTTTT","shouldOverrideUrlLoading.url:"+url);
                return true;
            }

        });
        //回退
//        contentView.setOnKeyListener(onKeyListener);

        if(HttpUtil.isWIFI == false){
            contentView.getSettings().setBlockNetworkImage(Settings.getsInstance().getBoolean(Settings.NO_PIC_MODE,false));
        }else {
            contentView.getSettings().setBlockNetworkImage(false);
        }

        networkBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                networkBtn.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                onDataRefresh();
            }
        });

        onDataRefresh();

    }

    protected  void onPageFinished(WebView view, String url){

    }
    protected void loadSetings(){

    }

    private View.OnKeyListener onKeyListener = new View.OnKeyListener(){
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if(event.getAction() == KeyEvent.ACTION_UP){
                if(keyCode == KeyEvent.KEYCODE_BACK && contentView.canGoBack()){
                    contentView.goBack();
                    return true;
                }
            }
            return false;
        }
    };
    @Override
    protected void onPause() {
        super.onPause();
        if(contentView != null){
            contentView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(contentView != null){
            contentView.destroy();
        }
    }

    protected int getLayoutID(){
        return R.layout.activity_base_details;
    }

    protected void setMainContentBg(final String url){
        if(Utils.hasString(url) == false){
            setDefaultColor();
            return;
        }

        Request.Builder builder = new Request.Builder();
        builder.url(url);
        final Request request = builder.build();
        progressBarTopPic.setVisibility(View.VISIBLE);
        HttpUtil.enqueue(request, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        setDefaultColor();
                    }
                });
            }

            @Override
            public void onResponse(Response response) throws IOException {
                final Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        if(bitmap == null){
                            setDefaultColor();
                            return;
                        }
                        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
                            topImage.setBackground(new BitmapDrawable(getResources(), bitmap));
                        }else {
                            topImage.setImageURI(Uri.parse(url));
                        }
                        progressBarTopPic.setVisibility(View.GONE);
                    }
                });
            }
        });

    }

    public void hideContentLoading(){
        if(progressBar != null){
            progressBar.setVisibility(View.GONE);
        }
    }

    public void hidePicLoading(){
        if(progressBarTopPic != null){
            progressBarTopPic.setVisibility(View.GONE);
        }
    }

    public void displayNetworkError(){
        if(networkBtn != null){
            networkBtn.setVisibility(View.VISIBLE);
        }
    }
    protected void setDefaultColor(){
        mainContent.setBackgroundColor(Color.rgb(67,76,66));
        hidePicLoading();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_share,menu);
        updateCollectionMenu(menu.findItem(R.id.menu_collect));
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == R.id.menu_share){
            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            startActivity(Intent.createChooser(sharingIntent,getString(R.string.hint_share_to)));
            return super.onOptionsItemSelected(item);
        }else if(item.getItemId() == R.id.menu_collect){
            if(isCollected){
                removeFromCollection();
                isCollected = false;
                updateCollectionMenu(item);
                Snackbar.make(mainContent,R.string.notify_remove_from_collection,Snackbar.LENGTH_SHORT).show();
            }else {
                addToCollection();
                isCollected = true;
                updateCollectionMenu(item);
                Snackbar.make(mainContent,R.string.notify_add_to_collection,Snackbar.LENGTH_SHORT).show();
            }
        }
        return true;
    }

    protected void updateCollectionMenu(MenuItem item){
        if(isCollected){
            item.setIcon(R.drawable.ic_star_black);
        }else {
            item.setIcon(R.drawable.ic_star_white);
        }
    }
    protected abstract void removeFromCollection();
    protected abstract void addToCollection();
    protected abstract String getShareInfo();
}
